013. Roman to Integer

问题

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

Subscribe to see which companies asked this question

思路

首先要知道罗马数字的规律:

Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1,000

然后还有一个规则是,罗马数字从左自右相加,但是如果小数字A在大数字B之前,表示B-A

VI = 5+1 = 6
IV = 5-1 = 4

因此,利用2个变量保存当前数字和之前的数字就行了。因为这题很简单,用python比较方便,我就用python做的

  1. class Solution(object):
  2. def romanToInt(self, s):
  3. sum=0
  4. pre = 2000
  5. cur = 0
  6. Map = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
  7. for i in range(len(s)):
  8. cur = Map[s[i]]
  9. sum = sum+Map[s[i]]
  10. if cur > pre :
  11. sum = sum-2*pre
  12. pre = cur
  13. return sum